package cn.fl.capital.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.*;
import cn.fl.audit.service.IAudCreditInfoService;
import cn.fl.capital.condition.CapOverdueInfoQueryCondition;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.service.ICapFundVfLogService;
import cn.fl.capital.service.ICapOverdueInfoService;
import cn.fl.capital.utils.ExportFundList;
import cn.fl.capital.vo.CapFundVfLogVO;
import cn.fl.capital.vo.CapOverdueInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.risk.service.IRskRentRemindService;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @Description: 逾期信息表 控制层
 */
@Controller
@RequestMapping("/capital/capOverdueInfo")
public class CapOverdueInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CapOverdueInfoController.class);

    /**
     * CapOverdueInfo 服务层BEAN
     */
    @Autowired
    private ICapOverdueInfoService capOverdueInfoService;
    @Autowired
    private ICapFundVfLogService capFundVfLogService;
    @Autowired
    private IRskRentRemindService rskRentRemindService;

	@Autowired
	private IAudCreditInfoService audCreditInfoService;
    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载CapOverdueInfo列表页面.", CurrentThreadContext.getCurrentUserName());
        //TODO 2017-12-12 ZT 加入货物种类
        List<KeyValueVO> searchPrdTypCdList = this.rskRentRemindService.searchPrdTypCdList();
        
      	//主货物大类
    	List<KeyValueVO> mainGdsTypCdList = this.audCreditInfoService.searchGoodsTypListByLvl("1");
    	
        ModelAndView mav = new ModelAndView("capital/capOverdueInfo/capOverdueInfoList");
        mav.addObject("mainGdsTypCdList", mainGdsTypCdList);
        mav.addObject("prdTypCdList", JSON.toJSONString(searchPrdTypCdList));
        return mav;
    }

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toCstOvdListPage.do", method = {RequestMethod.GET})
    public ModelAndView toCstOvdListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toCstOvdListPage", "加载客户支付表逾期明细列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capOverdueInfo/capCstOvdInfoList");
        return mav;
    }

    /*************************
     * 到罚息减免页面
     *************************/
    @RequestMapping(value = "/toReductionPage.do", method = {RequestMethod.GET})
    public ModelAndView toReductionPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toReductionPage", "加载到罚息减免页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capOverdueInfo/capFineReduction");
        String cstId = request.getParameter("cstId");//客户ID
        String vfId = request.getParameter("vfId");//减免罚息业务主键ID
        String ctrlKey = request.getParameter("ctrlKey");//控制键 0：只能选择 1.选择保存 2.选择并修改金额
        mav.addObject("cstId", cstId);
        mav.addObject("vfId", vfId);
        mav.addObject("ctrlKey", ctrlKey);
        if (StringUtils.isNotEmpty(vfId)) {
            CapFundVfLogVO logVO = this.capFundVfLogService.selectById(Long.valueOf(vfId));
            if (null != logVO) {
                mav.addObject("vfAmt", DecimalUtils.convertFenToYuan(logVO.getVfAmt()));
            }
        }
        return mav;
    }

    /***************************************
     * 减免罚息，查询客户逾期支付表汇总信息
     ***************************************/
    @RequestMapping(value = "/initOvdPayList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initOvdPayList(HttpServletRequest request, HttpServletResponse response) {
        String cstId = request.getParameter("cstId");//客户ID
        String vfId = request.getParameter("vfId");//减免流程业务主键
        CapOverdueInfoQueryCondition condition = new CapOverdueInfoQueryCondition();
        if (StringUtils.isNotEmpty(cstId)) {
            condition.setCstId(Long.valueOf(cstId));
        }
        if (StringUtils.isNotEmpty(vfId)) {
            condition.setVfId(Long.valueOf(vfId));
        }
        condition.setCreateDate(DateUtils.formatDate(new Date(), DateUtils.YYYY_MM_DD));
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
        BaseLogUtils.info(logger, "initOvdPayList", "查询客户逾期支付表汇总信息.DATA:" + JSONObject.toJSONString(condition), CurrentThreadContext.getCurrentUserName());
        List<CapOverdueInfoVO> list = this.capOverdueInfoService.searchOvdPayList(condition);
        return new ListPageVO<CapOverdueInfoVO>(list, list.size());
    }

    /**************************
     * 减免罚息，查询客户支付表逾期明细
     **************************/
    @RequestMapping(value = "/initOvdDtlList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initOvdDtlList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(currentPage)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        String cstId = request.getParameter("cstId");//客户ID
        String paySchId = request.getParameter("paySchId");//逾期支付表ID
        CapOverdueInfoQueryCondition condition = new CapOverdueInfoQueryCondition();
        if (StringUtils.isNotEmpty(cstId)) {
            condition.setCstId(Long.valueOf(cstId));
        }
        if (StringUtils.isNotEmpty(paySchId)) {
            condition.setPaySchId(Long.valueOf(paySchId));
        }
        condition.setSortName("createDate");
        condition.setSortOrder("desc");

        page.setCondition(condition);
        BaseLogUtils.info(logger, "initCapOverdueInfoList", "查询客户逾期支付表汇总信息.DATA:" + JSONObject.toJSONString(condition), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.capOverdueInfoService.searchOvdDtlListPage(page);
        List<CapOverdueInfoVO> list = (List<CapOverdueInfoVO>) pager.getResultList();
        ListPageVO<CapOverdueInfoVO> listPage = new ListPageVO<CapOverdueInfoVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**************************
     * 减免罚息，查询客户支付表逾期明细 不分页
     **************************/
    @RequestMapping(value = "/initOvdPayDtlList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initOvdPayDtlList(HttpServletRequest request, HttpServletResponse response) {
        String cstId = request.getParameter("cstId");//客户ID
        String paySchId = request.getParameter("paySchId");//逾期支付表ID
        CapOverdueInfoQueryCondition condition = new CapOverdueInfoQueryCondition();
        if (StringUtils.isNotEmpty(cstId)) {
            condition.setCstId(Long.valueOf(cstId));
        }
        if (StringUtils.isNotEmpty(paySchId)) {
            condition.setPaySchId(Long.valueOf(paySchId));
        }
        condition.setSortName("createDate");
        condition.setSortOrder("desc");
        BaseLogUtils.info(logger, "initOvdPayDtlList", "减免罚息，查询客户支付表逾期明细.DATA:" + JSONObject.toJSONString(condition), CurrentThreadContext.getCurrentUserName());
        List<CapOverdueInfoVO> list = this.capOverdueInfoService.searchPayDtlList(condition);
        if (CollectionUtils.isNotEmpty(list)) {
            return new ListPageVO<CapOverdueInfoVO>(list, list.size());
        }
        return null;
    }

    /**
     * 到还款明细页面
     */
    @RequestMapping(value = "/toRepaymentDtl.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toRepaymentDtl(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toRepaymentDtl", "加载到还款明细页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capOverdueInfo/capRepaymentDtlList");
        //加载数据字典数据、传值等 ？
        String cstId = request.getParameter("cstId");
        String cstNm = request.getParameter("cstNm");
        mav.addObject("cstId", cstId);
        mav.addObject("cstNm", cstNm);
        return mav;
    }

    /**
     * 到逾期明细页面
     */
    @RequestMapping(value = "/toOverdueDtl.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toOverdueDtl(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toModifyPage", "加载到逾期明细页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capOverdueInfo/capOverdueDtlList");
        //加载数据字典数据、传值等 ？
        String cstId = request.getParameter("cstId");
        String cstNm = request.getParameter("cstNm");
        mav.addObject("cstId", cstId);
        mav.addObject("cstNm", cstNm);
        return mav;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initCapOverdueInfoList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(currentPage)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        CapOverdueInfoQueryCondition qc = new CapOverdueInfoQueryCondition();
        //设置查询条件？
        String cstNm = request.getParameter("cstNm");
        String paySchNo = request.getParameter("paySchNo");
        String dayMin = request.getParameter("overdueDayMin");
        String dayMax = request.getParameter("overdueDayMax");
        String payDtSt = request.getParameter("payDtSt");
        String payDtEd = request.getParameter("payDtEd");
        String paySchId = request.getParameter("paySchId");
        String cstId = request.getParameter("cstId");

        if (StringUtils.isNotEmpty(paySchId)){
            qc.setPaySchId(Long.parseLong(paySchId));
        }
        if (StringUtils.isNotEmpty(cstId)){
            qc.setCstId(Long.parseLong(cstId));
        }
        if (StringUtils.isNotEmpty(cstNm)) {
            qc.setCstNm(cstNm);
        }
        if (StringUtils.isNotBlank(paySchNo)) {
            qc.setPaySchNo(paySchNo);
        }
        if (StringUtils.isNotEmpty(dayMax)) {
            qc.setOverdueDayMax(Long.valueOf(dayMax));
        }
        if (StringUtils.isNotEmpty(dayMin)) {
            qc.setOverdueDayMin(Long.valueOf(dayMin));
        }
        if (StringUtils.isNotEmpty(payDtSt)) {
            qc.setPayDtSt(DateUtils.formatStringToDate(payDtSt, DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotEmpty(payDtEd)) {
            qc.setPayDtEd(DateUtils.formatStringToDate(payDtEd, DateUtils.YYYY_MM_DD));
        }
        page.setCondition(qc);

        BaseLogUtils.info(logger, "initCapOverdueInfoList", "初始化CapOverdueInfo列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.capOverdueInfoService.searchListPage(page);
        List<CapOverdueInfoVO> list = (List<CapOverdueInfoVO>) pager.getResultList();
        ListPageVO<CapOverdueInfoVO> listPage = new ListPageVO<CapOverdueInfoVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 初始化明细列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/searchDtlList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object searchDtlList(HttpServletRequest request, HttpServletResponse response) {
        CapOverdueInfoQueryCondition qc = new CapOverdueInfoQueryCondition();
        //设置查询条件？
        String cstId = request.getParameter("cstId");
        if (StringUtils.isNotEmpty(cstId)) {
            qc.setCstId(Long.valueOf(cstId));
        }
        BaseLogUtils.info(logger, "searchDtlList", "初始化searchDtlList明细列表页面数据.DATA:{cstId:" + cstId + "}", CurrentThreadContext.getCurrentUserName());
        List<CapOverdueInfoVO> list = this.capOverdueInfoService.searchList(qc);
        ListPageVO<CapOverdueInfoVO> listPage = new ListPageVO<CapOverdueInfoVO>(list, list.size());
        return listPage;
    }

    /**
     * 逾期明细列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/searchDtlListByCstId.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object searchDtlListByCstId(HttpServletRequest request, HttpServletResponse response) {
        CapOverdueInfoQueryCondition qc = new CapOverdueInfoQueryCondition();
        //设置查询条件？
        String cstId = request.getParameter("cstId");
        if (StringUtils.isNotEmpty(cstId)) {
            qc.setCstId(Long.valueOf(cstId));
        }else{
            return new ListPageVO<CapOverdueInfoVO>(new ArrayList<CapOverdueInfoVO>(), 0);
        }
        BaseLogUtils.info(logger, "searchDtlListByCstId", "初始化逾期明细列表页面数据.DATA:{cstId:" + cstId + "}", CurrentThreadContext.getCurrentUserName());
        qc.setDataStatusCd(CapitalConstant.CODE_OVD_DATA_CD_0);
        qc.setCreateDate(new Date());
        List<String> stsCdList = new ArrayList<>(2);
        stsCdList.add(CapitalConstant.CODE_OVD_STATUS_CD_0);
        stsCdList.add(CapitalConstant.CODE_OVD_STATUS_CD_1);
        qc.setOverdueStatusCdList(stsCdList);
        List<CapOverdueInfoVO> list = this.capOverdueInfoService.searchDtlList(qc);
        ListPageVO<CapOverdueInfoVO> listPage = new ListPageVO<CapOverdueInfoVO>(list, list.size());
        return listPage;
    }


    /**
     * 导出逾期
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/exportOverdue.do", method = {RequestMethod.GET})
    public void exportFundDecom(HttpServletRequest request, HttpServletResponse response) {
        CapOverdueInfoQueryCondition qc = new CapOverdueInfoQueryCondition();
        //设置查询条件？
        String format = request.getParameter("format");
        String cstNm = request.getParameter("cstNm");
        String paySchNo = request.getParameter("paySchNo");
        String dayMin = request.getParameter("overdueDayMin");
        String dayMax = request.getParameter("overdueDayMax");
        String payDtSt = request.getParameter("payDtSt");
        String payDtEd = request.getParameter("payDtEd");

        if (StringUtils.isNotEmpty(cstNm)) {
            qc.setCstNm(cstNm);
        }
        if (StringUtils.isNotBlank(paySchNo)) {
            qc.setPaySchNo(paySchNo);
        }
        if (StringUtils.isNotEmpty(dayMax)) {
            qc.setOverdueDayMax(Long.valueOf(dayMax));
        }
        if (StringUtils.isNotEmpty(dayMin)) {
            qc.setOverdueDayMin(Long.valueOf(dayMin));
        }
        if (StringUtils.isNotEmpty(payDtSt)) {
            qc.setPayDtSt(DateUtils.formatStringToDate(payDtSt, DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotEmpty(payDtEd)) {
            qc.setPayDtEd(DateUtils.formatStringToDate(payDtEd, DateUtils.YYYY_MM_DD));
        }

        BaseLogUtils.info(logger, "exportFundDecom", "查询导出逾期的数据.DATA:" + JSONObject.toJSONString(qc), CurrentThreadContext.getCurrentUserName());
        List<CapOverdueInfoVO> list = this.capOverdueInfoService.searchOverdueList(qc);
        if (CollectionUtils.isNotEmpty(list)) {
            Map<String, Object> map = new HashMap<>();
            map.put("overdueList", list);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            String filename = "逾期催收";
            response.setCharacterEncoding("utf-8");
            OutputStream os = null;
            try {
                filename = new String(filename.getBytes("utf-8"), "ISO8859-1");
                if ("pdf".equals(format)) {
                    response.setHeader("Content-disposition", "attachment; filename=" + filename + ".pdf");// 设定输出文件头
                    response.setContentType("application/pdf");// 定义输出类型
                    baos = new ExportFundList().exportOverDuePdf(map);
                } else {
                    response.setHeader("Content-disposition", "attachment; filename=" + filename + ".xls");// 设定输出文件头
                    response.setContentType("application/x-msdownload");// 定义输出类型
                    baos = new ExportFundList().exportOverDueXls(map);
                }
                os = response.getOutputStream();
                baos.writeTo(os);
                baos.flush();
                os.flush();
            } catch (UnsupportedEncodingException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
            } catch (IOException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
            } finally {
                //关闭流
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
                    }
                }
                if (baos != null) {
                    try {
                        baos.close();
                    } catch (IOException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
                    }
                }
            }
        }
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeCapOverdueInfoByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeCapOverdueInfoByIds", "删除CapOverdueInfo数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }

        try {
            boolean success = this.capOverdueInfoService.removeByIds(idsList);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
                BaseLogUtils.info(logger, "removeCapOverdueInfoByIds", "删除CapOverdueInfo数据失败,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "removeCapOverdueInfoByIds", "删除CapOverdueInfo数据成功,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "removeCapOverdueInfoByIds", "删除CapOverdueInfo数据失败,ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "removeCapOverdueInfoByIds", "删除CapOverdueInfo数据失败,系统错误.ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getCapOverdueInfoById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "getCapOverdueInfoById", "获取CapOverdueInfo数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            CapOverdueInfoVO vo = this.capOverdueInfoService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "getCapOverdueInfoById", "获取CapOverdueInfo数据不存在,ID:" + id, CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getCapOverdueInfoById", "获取CapOverdueInfo数据成功,ID:" + id, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "getCapOverdueInfoById", "获取CapOverdueInfo数据失败,ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getCapOverdueInfoById", "获取CapOverdueInfo数据失败,系统错误.ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addCapOverdueInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        CapOverdueInfoVO entity = null;//获取参数
        try {
            entity = this.getRequestParamForCapOverdueInfo(request);//获取参数
            Long id = this.capOverdueInfoService.add(entity);
            result.setData(id);
            BaseLogUtils.info(logger, "addCapOverdueInfo", "新增CapOverdueInfo数据成功,ID:" + id + ".DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "addCapOverdueInfo", "新增CapOverdueInfo数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "addCapOverdueInfo", "新增CapOverdueInfo数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modifyCapOverdueInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        CapOverdueInfoVO entity = null;
        try {
            entity = this.getRequestParamForCapOverdueInfo(request);
            if (entity.getId() == null) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
                BaseLogUtils.info(logger, "modifyCapOverdueInfo", "修改CapOverdueInfo信息,主键参数为空！.ID:" + entity.getId(), CurrentThreadContext.getCurrentUserName());
                return result;
            }

            boolean success = this.capOverdueInfoService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                BaseLogUtils.info(logger, "modifyCapOverdueInfo", "修改CapOverdueInfo数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            BaseLogUtils.info(logger, "modifyCapOverdueInfo", "修改CapOverdueInfo数据成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "modifyCapOverdueInfo", "修改CapOverdueInfo数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "modifyCapOverdueInfo", "修改CapOverdueInfo数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return
     */
    private CapOverdueInfoVO getRequestParamForCapOverdueInfo(HttpServletRequest request) throws BaseException {
        //获取参数
        String id = request.getParameter("id");//主键
        String cstId = request.getParameter("cstId");
        String paySchId = request.getParameter("paySchId");
        String payPd = request.getParameter("payPd");
        String overdueDate = request.getParameter("overdueDate");
        String overdueDay = request.getParameter("overdueDay");
        String overdueAmount = request.getParameter("overdueAmount");
        String overdueRate = request.getParameter("overdueRate");
        String payAmount = request.getParameter("payAmount");
        String penaltyAmount = request.getParameter("penaltyAmount");
        String dataStatusCd = request.getParameter("dataStatusCd");
        String overdueStatusCd = request.getParameter("overdueStatusCd");
        String remark = request.getParameter("remark");
        String createTime = request.getParameter("createTime");


        //验证参数并赋值
        CapOverdueInfoVO entity = new CapOverdueInfoVO();


//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }
//      entity.setX();

        Date tm = new Date();
        if (StringUtils.isNotBlank(id)) {
            entity.setId(Long.valueOf(id));
            entity.setMdfTm(tm);
            entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        } else {
            entity.setCrtTm(tm);
            entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        }

        return entity;
    }


    @RequestMapping(value = "/calcOvd.do", method = {RequestMethod.GET})
    @ResponseBody
    public DataResultVO calcCapOverdueInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "逾期计算完成...");
        String cstId = request.getParameter("cstId");//客户ID
        String paySchId = request.getParameter("paySchId");//支付表表
        String all = request.getParameter("all");
        if(StringUtils.isEmpty(cstId)&&StringUtils.isEmpty(paySchId)&&StringUtils.isBlank(all)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("请提供客户ID(cstId)或者支付表ID(paySchId)...");
            return result;
        }

        CapOverdueInfoQueryCondition condition = new CapOverdueInfoQueryCondition();
        if (StringUtils.isNotEmpty(cstId)) {
            condition.setCstId(Long.valueOf(cstId.trim()));
        }
        if (StringUtils.isNotEmpty(paySchId)) {
            condition.setPaySchId(Long.valueOf(paySchId.trim()));
        }
        boolean flag = this.capOverdueInfoService.addOvdInfo(condition);
        if (flag) {
            return result;
        } else {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("逾期计算正在执行....");
        }
        return result;
    }

    /**
     * 计算客户应付金额
     *
     * @param request
     * @param response
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = "/calcCstOvdAmt.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO calcCstOvdAmt(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "计算完成");
        String createDate = request.getParameter("createDate");//罚息日期
        String cstId = request.getParameter("cstId");//客户ID
        if(StringUtils.isBlank(createDate)||StringUtils.isBlank(cstId)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("未找到客户信息");
            return result;
        }

        BaseLogUtils.info(logger,"calcCstOvdAmt","计算客户["+cstId+"]["+createDate+"]应付金额",CurrentThreadContext.getCurrentUserName());
        CapOverdueInfoQueryCondition condition=new CapOverdueInfoQueryCondition();
        condition.setCreateDate(DateUtils.formatStringToDate(createDate,DateUtils.YYYY_MM_DD));
        condition.setCstId(Long.valueOf(cstId));
        CapOverdueInfoVO vo = this.capOverdueInfoService.calcCstOvdAmt(condition);
        if(vo==null){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("计算客户应付金额异常");
        }else{
            result.setData(vo);
        }
        return result;
    }

    /**
     * 计算小贷逾期历史
     * @param request
     * @param response
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = "/calcMcrCapOverdueHis.do", method = {RequestMethod.GET})
    @ResponseBody
    public DataResultVO calcMcrCapOverdueHis(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "小贷逾期历史计算完成...");
        String cstId = request.getParameter("cstId");//客户ID
        if(StringUtils.isEmpty(cstId)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("请提供客户ID(cstId)");
            return result;
        }
        BaseLogUtils.info(logger,"calcMcrCapOverdueHis","计算客户小贷逾期历史请求参数cstId:"+ cstId);

        CapOverdueInfoQueryCondition condition = new CapOverdueInfoQueryCondition();
        if (StringUtils.isNotEmpty(cstId)) {
            condition.setCstId(Long.valueOf(cstId.trim()));
        }
        try{
            this.capOverdueInfoService.calcMcrCapOverdueHis(condition);
        }catch (BaseException e){
            BaseLogUtils.info(logger,"calcMcrCapOverdueHis","计算客户小贷逾期历史异常:"+ JSONObject.toJSONString(e.getMessage()));
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(e.getMessage());
        }catch (Exception e){
            BaseLogUtils.info(logger,"calcMcrCapOverdueHis","计算客户小贷逾期历史异常:"+ JSONObject.toJSONString(e.getMessage()));
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(e.getMessage());
        }
        return result;
    }
}

